<template>
  <div class="event-detail">
    <div class="container">
      <!-- 演出基本信息 -->
      <div class="event-header">
        <div class="event-image">
          <img v-lazy="{ src: event.image, fallback: `${BASE_URL}/images/phantom-opera.svg` }" :alt="event.title" />
          <div class="event-badge">{{ event.badge }}</div>
        </div>
        <div class="event-info">
          <h1>{{ event.title }}</h1>
          <div class="event-meta">
            <p><span class="icon">📍</span>{{ event.venue }}</p>
            <p><span class="icon">📅</span>{{ formatDate(event.date) }}</p>
            <p><span class="icon">🎭</span>{{ event.category }}</p>
          </div>
          <div class="event-description">
            <p>{{ event.description }}</p>
          </div>
        </div>
      </div>

      <!-- 票价展示 -->
      <div class="ticket-section">
        <h2>票价信息</h2>
        <div class="ticket-types">
          <div 
            v-for="ticket in ticketTypes" 
            :key="ticket.id"
            class="ticket-type clickable"
            @click="openPurchaseModalWithTicket(ticket)"
          >
            <div class="ticket-info">
              <div class="ticket-name">{{ ticket.name }}</div>
              <div class="ticket-price">¥{{ ticket.price }}</div>
            </div>
            <div class="ticket-available">剩余 {{ ticket.available }} 张</div>
            <div class="ticket-click-hint">点击选座购买</div>
          </div>
        </div>
      </div>

      <!-- 购买操作区 -->
      <div class="purchase-section">
        <div class="purchase-actions">
          <button class="btn btn-primary" @click="openPurchaseModal" :disabled="ticketTypes.length === 0">
            立即购买
          </button>
          <button class="btn btn-outline" @click="toggleFavorite">
            {{ isFavorite ? '已收藏' : '收藏' }}
          </button>
        </div>
      </div>

      <!-- 返回按钮 -->
      <div class="back-section">
        <router-link to="/events" class="btn btn-outline">返回演出列表</router-link>
      </div>
    </div>

    <!-- 购票弹窗 -->
    <TicketPurchaseModal 
      :visible="showPurchaseModal"
      :event="event"
      :ticket-types="ticketTypes"
      :initial-ticket="initialTicketForModal"
      :initial-step="initialStepForModal"
      @close="closePurchaseModal"
      @purchase-success="onPurchaseSuccess"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { useActivityStore } from '@/stores/activity'
import { apiClient, BASE_URL } from '@/api/client'
import TicketPurchaseModal from '@/components/TicketPurchaseModal.vue'

const route = useRoute()
const activityStore = useActivityStore()

// 演出信息
const event = ref({
  id: null,
  title: '',
  venue: '',
  date: '',
  category: '',
  image: '/src/assets/images/swan-lake.svg',
  badge: '',
  description: ''
})

// 票价类型
const ticketTypes = ref([])

// 购票弹窗状态
const showPurchaseModal = ref(false)
// 预选票价与初始步骤（用于从票价卡片直接进入选座）
const initialTicketForModal = ref(null)
const initialStepForModal = ref(1)

// 收藏状态
const isFavorite = computed(() => activityStore.isFavorite(event.value.id))
const toggleFavorite = () => {
  if (!event.value?.id) return
  activityStore.toggleFavorite({
    id: event.value.id,
    title: event.value.title,
    image: event.value.image,
    date: event.value.date,
    venue: event.value.venue
  })
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    weekday: 'long'
  })
}

// 打开购票弹窗
const openPurchaseModal = () => {
  // 正常“立即购买”从步骤1开始，不预选票价
  initialTicketForModal.value = null
  initialStepForModal.value = 1
  showPurchaseModal.value = true
}

// 点击票价区域直接进入选座弹窗
const openPurchaseModalWithTicket = (ticket) => {
  if (ticket.available === 0) return // 如果票已售罄，不允许点击
  // 预选当前票价，并直接进入选座步骤
  initialTicketForModal.value = ticket
  initialStepForModal.value = 2
  showPurchaseModal.value = true
}

// 关闭购票弹窗
const closePurchaseModal = () => {
  showPurchaseModal.value = false
  // 关闭时重置预选信息
  initialTicketForModal.value = null
  initialStepForModal.value = 1
}

// 购买成功回调
const onPurchaseSuccess = (orderData) => {
  // 可以在这里添加购买成功后的逻辑
  console.log('购买成功:', orderData)
}

// 根据路由参数加载演出信息
onMounted(async () => {
  const eventId = route.params.id
  try {
    // 加载演出详情
    const response = await apiClient.get(`/api/events/${eventId}`)
    const e = response?.data
    if (e) {
      event.value = {
        id: e.id,
        title: e.title,
        venue: e.venue,
        date: e.startTime,
        category: e.category,
        image: e.posterUrl ? `${BASE_URL}${e.posterUrl}` : `${BASE_URL}/images/phantom-opera.svg`,
        badge: '',
        description: e.description || ''
      }
      // 记录最近浏览
      activityStore.addRecent({
        id: event.value.id,
        title: event.value.title,
        image: event.value.image,
        date: event.value.date,
        venue: event.value.venue
      })
    }
    // 加载可售票
    const ticketsResponse = await apiClient.get(`/api/events/${eventId}/tickets?status=1`)
  const tickets = ticketsResponse?.data
  ticketTypes.value = (tickets || []).map(t => ({
    id: t.id,
    name: `${t.ticketType} ${t.seatArea || ''} ${t.seatRow || ''} ${t.seatNumber || ''}`.trim(),
    ticketType: t.ticketType,
    price: t.price,
    available: 1
  }))

    // 若从列表页携带 buyNow 参数，则自动弹出购票流程
    if (route.query?.buyNow) {
      initialTicketForModal.value = null
      initialStepForModal.value = 1
      showPurchaseModal.value = true
    }
  } catch (err) {
    console.error('加载演出或票失败', err)
  }
})
</script>

<style scoped>
.event-detail {
  min-height: 100vh;
  background-color: #fafafa;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 24px 16px;
}

/* 演出头部信息 */
.event-header {
  display: grid;
  grid-template-columns: 300px 1fr;
  gap: 32px;
  margin-bottom: 48px;
  background: white;
  padding: 32px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.event-image {
  position: relative;
}

.event-image img {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 8px;
}

.event-badge {
  position: absolute;
  top: 8px;
  right: 8px;
  background-color: #e91e63;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.event-info h1 {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 16px;
  color: #212121;
}

.event-meta p {
  margin: 8px 0;
  color: #757575;
  display: flex;
  align-items: center;
}

.icon {
  margin-right: 8px;
  font-size: 16px;
}

.event-description {
  margin-top: 16px;
  line-height: 1.6;
  color: #424242;
}

/* 票价展示 */
.ticket-section {
  margin-bottom: 48px;
}

.ticket-section h2 {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 24px;
  color: #212121;
}

.ticket-types {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 16px;
}

.ticket-type {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: 1px solid #e0e0e0;
  transition: all 0.3s ease;
  position: relative;
}

.ticket-type.clickable {
  cursor: pointer;
}

.ticket-type.clickable:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  border-color: #e91e63;
}

.ticket-type.clickable:active {
  transform: translateY(0);
}

.ticket-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.ticket-name {
  font-weight: bold;
  color: #212121;
  font-size: 16px;
}

.ticket-price {
  font-size: 18px;
  font-weight: bold;
  color: #e91e63;
}

.ticket-available {
  font-size: 12px;
  color: #757575;
}

.ticket-click-hint {
  font-size: 11px;
  color: #e91e63;
  text-align: center;
  margin-top: 8px;
  opacity: 0.8;
  font-weight: 500;
}



/* 购买操作区 */
.purchase-section {
  margin-bottom: 48px;
  background: white;
  padding: 32px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.purchase-actions {
  display: flex;
  gap: 16px;
  justify-content: center;
}

/* 按钮样式 */
.btn {
  display: inline-block;
  padding: 12px 24px;
  border-radius: 8px;
  text-decoration: none;
  font-weight: 500;
  transition: all 0.3s ease;
  border: none;
  cursor: pointer;
  font-size: 14px;
}

.btn-primary {
  background-color: #e91e63;
  color: white;
}

.btn-primary:hover {
  background-color: #ad1457;
}

.btn-secondary {
  background-color: #9c27b0;
  color: white;
}

.btn-secondary:hover {
  background-color: #7b1fa2;
}

.btn-outline {
  background-color: transparent;
  color: #757575;
  border: 1px solid #e0e0e0;
}

.btn-outline:hover {
  background-color: #f5f5f5;
}

.back-section {
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .event-header {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .ticket-types {
    grid-template-columns: 1fr;
  }
  
  .seat-grid {
    grid-template-columns: repeat(8, 1fr);
  }
  
  .purchase-actions {
    flex-direction: column;
  }
}
</style>